import api from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
// import router, { resetRouter } from '@/router'


const state = {
  id: '',
  username: '',
  nickname: '',
  real_name: '',
  gender: '',  // 0:未知 1:女 2:男
  email: '',
  avatar: '',
  date_joined: '',
  last_login: ''
}

const getters = {}

const mutations = {
  SET_INFO: (state, {key, value}) => {
    if(Object.prototype.hasOwnProperty.call(state, key)){
      state[key] = value
    }
  }
}

const actions = {
  // user login
  login(context, userInfo) {
    const { username, password } = userInfo
    return api.login(username.trim(), password).then(response => {
      setToken(response.data)
    })
  },

  // user logout
  logout({ dispatch }) {
    const token = getToken()
    let refreshToken = ''
    if(token && token['refresh_token']){
      refreshToken = token['refresh_token']
    }
    return api.logout(refreshToken).catch((e) => {
      console.log('退出异常：', e)
    }).finally(() => {
      removeToken()
      resetRouter()
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
    })
  },

  // get self info
  getSelfInfo({ commit }) {
    return api.getSelfInfo().then(response => {
      const data = response.data
      Object.keys(data).forEach(key => {
        commit('SET_INFO', {
          key: key,
          value: data[key]
        })
      })
    })
  },

  // set self info
  setUserInfo({commit}, info) {
    return api.setUserInfo(info).then(response => {
      const data = response.data
      Object.keys(data).forEach(key => {
        commit('SET_INFO', {
          key: key,
          value: data[key]
        })
      })
    })
  },

  // set user avatar
  setUserAvatar({commit}, payload) {
    return api.setUserAvatar(payload).then(response => {
      const data = response.data
      Object.keys(data).forEach(key => {
        commit('SET_INFO', {
          key: key,
          value: data[key]
        })
      })
    })
  },

  // set self password
  setSelfPassword(context, {oldPassword, newPassword}) {
    return api.setSelfPassword(oldPassword, newPassword)
  }

  // // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const data = response.data
  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }
  //       data['roles'] = ['admin']
  //       // const { roles , name, avatar } = data
  //       const { roles, username, nickname, avatar } = data
  //       // roles must be a non-empty array
  //       if (!roles || roles.length <= 0) {
  //         reject('getInfo: roles must be a non-null array!')
  //       }
  //
  //       commit('SET_ROLES', roles)
  //       commit('SET_NAME', nickname || username)
  //       commit('SET_AVATAR', avatar)
  //       commit('SET_INTRODUCTION', '')
  //       resolve(data)
  //     }).catch(error => {
  //       reject('用户信息获取失败', error)
  //     })
  //   })
  // },

  // // remove token
  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     commit('SET_ROLES', [])
  //     removeToken()
  //     resolve()
  //   })
  // },
  //
  // // dynamically modify permissions
  // async changeRoles({ commit, dispatch }, role) {
  //   const { roles } = await dispatch('getInfo')
  //
  //   resetRouter()
  //
  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)
  //
  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, { root: true })
  // }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
